﻿//-----------------------------------------------------------------------
// <copyright file="AsAUserWhenISaveAnImageIntoTheRepositoryIShouldBeAbleToSeeTheImageViaDownloadHandler.cs" company="OOHM PROCESSAMENTO DE DADOS LTDA.">
//     Microsoft Public License (MS-PL) This license governs use of the accompanying
//     software. If you use the software, you accept this license. If you do not
//     accept the license, do not use the software. 1. Definitions The terms "reproduce,"
//     "reproduction," "derivative works," and "distribution" have the same meaning
//     here as under U.S. copyright law. A "contribution" is the original software,
//     or any additions or changes to the software. A "contributor" is any person
//     that distributes its contribution under this license. "Licensed patents"
//     are a contributor's patent claims that read directly on its contribution.
//     2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3, each contributor
//     grants you a non-exclusive, worldwide, royalty-free copyright license to
//     reproduce its contribution, prepare derivative works of its contribution,
//     and distribute its contribution or any derivative works that you create.
//     (B) Patent Grant- Subject to the terms of this license, including the license
//     conditions and limitations in section 3, each contributor grants you a non-exclusive,
//     worldwide, royalty-free license under its licensed patents to make, have
//     made, use, sell, offer for sale, import, and/or otherwise dispose of its
//     contribution in the software or derivative works of the contribution in
//     the software. 3. Conditions and Limitations (A) No Trademark License- This
//     license does not grant you rights to use any contributors' name, logo, or
//     trademarks. (B) If you bring a patent claim against any contributor over
//     patents that you claim are infringed by the software, your patent license
//     from such contributor to the software ends automatically. (C) If you distribute
//     any portion of the software, you must retain all copyright, patent, trademark,
//     and attribution notices that are present in the software. (D) If you distribute
//     any portion of the software in source code form, you may do so only under
//     this license by including a complete copy of this license with your distribution.
//     If you distribute any portion of the software in compiled or object code
//     form, you may only do so under a license that complies with this license.
//     (E) The software is licensed "as-is." You bear the risk of using it. The
//     contributors give no express warranties, guarantees or conditions. You may
//     have additional consumer rights under your local laws which this license
//     cannot change. To the extent permitted under your local laws, the contributors
//     exclude the implied warranties of merchantability, fitness for a particular
// </copyright>
//-----------------------------------------------------------------------
namespace AbstractSaaSTemplate.Utility.Tests.UI.Web.Behaviour.Tenant{    using System;
    using System.Collections.Generic;
    using System.Web;
    using AbstractSaaSTemplate.Application.Framework;
    using AbstractSaaSTemplate.Domain.Models.Entities;
    using AbstractSaaSTemplate.Domain.Repositories;
    using AbstractSaaSTemplate.Kernel.Factories;
    using AbstractSaaSTemplate.UI.Web.Content.Blobs;
    using AbstractSaaSTemplate.UI.Web.Controllers;
    using AbstractSaaSTemplate.Utility.Tests.UI.Utilities;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    /// <summary>
    /// @14179835
    /// Implementar Mock Repository para Imagens e, utilizando este
    /// MockRepository, ser capaz de baixar estes arquivos através
    /// de um Handler (.axd) os arquivos que foram gravados neste
    /// repositório.
    /// </summary>
    [TestClass]
    public class TestFor14179835
    {
        #region Properties
        
        /// <summary>
        /// Gets or sets the repository to operate 'Blobs'.
        /// </summary>
        private IBlobRepository BlobsRepository { get; set; }

        /// <summary>
        /// Gets or sets the 'Home' controller.
        /// </summary>
        private HomeController HomeController { get; set; }

        #endregion

        #region Setup

        /// <summary>
        /// This method initializes controllers and dependencies for run tests.
        /// </summary>
        [TestInitialize]
        public void Setup()
        {
            TestFor0013453151.EnsureInstallationIsComplete();
            
            var factory = new ApplicationFactory();

            this.HomeController = factory.CreateControllerFor<HomeController>();
            
            this.BlobsRepository = factory.CreateRepositoryFor<IBlobRepository>();
        }

        #endregion

        /// <summary>
        /// @14179835
        /// Implementar Mock Repository para Imagens e, utilizando este
        /// MockRepository, ser capaz de baixar estes arquivos através
        /// de um Handler (.axd) os arquivos que foram gravados neste
        /// repositório.
        /// Passos da Mímica --------------------------------------------------
        /// 1.  Salvar arquivo usando repositório de arquivos
        ///     Deve assegurar:
        ///     1.1) Que o arquivo foi salvo.
        /// 2.  Fazer download do arquivo via Handler.
        ///     Deve assegurar:
        ///     2.1) Que sem id no QueryString é retornado o status code 500
        ///     2.2) Que com id errado (auy54y), é retornado um 404
        ///     2.3) Que com id errado (Guid.Empty()), é returnado um 404
        ///     2.4) Que com id correto foi possível retornar o arquivo 1 vez.
        ///     2.5) Que com id correto Que foi possível retornar o arquivo uma 2a vez.
        /// </summary>
        [TestMethod]
        public void AsAUserWhenISaveAnImageIntoTheRepositoryIShouldBeAbleToSeeTheImageViaDownloadHandler()
        {
            /* =========================================================
             * EXECUÇÃO DA MÍMICA
             * =========================================================
             * Os procedimentos executados à seguir são uma mímica dos
             * procedimentos executados pelos usuários no uso real do sistema.
             * ========================================================= */

            // 1)
            var blobId = this.UploadBlobToRepositoryAndAssertsItFunctions();

            // 2)
            this.AttemptToRunTheHandlerAndReceiveTheCorrectHttpContextParameters(blobId);
        }

        /// <summary>
        /// 1.  Salvar arquivo usando repositório de arquivos
        ///     Deve assegurar:
        ///     1.1) Que o arquivo foi salvo.
        /// </summary>
        /// <returns>Returns an instance of the blob created.</returns>
        private Blob UploadBlobToRepositoryAndAssertsItFunctions()
        {
            var resourceBlob = Resources.ImageForTest.ToStream();
            var blob = new Blob()
            {
                Stream = resourceBlob,
                OriginalName = "image-for-test.png",
                ContentType = "image/png"
            };

            this.BlobsRepository.AddOrUpdateBlob(blob);
            Assert.AreNotEqual<Guid>(Guid.Empty, blob.Id);
            return blob;
        }
        
        /// <summary>
        /// 2.  Fazer download do arquivo via Handler.
        ///     Deve assegurar:
        ///     2.1) Que sem id no QueryString é retornado o status code 500
        ///     2.2) Que com id errado (auy54y), é retornado um 404
        ///     2.3) Que com id errado (Guid.Empty()), é returnado um 404
        ///     2.4) Que com id correto foi possível retornar o arquivo 1 vez.
        ///     2.5) Que com id correto Que foi possível retornar o arquivo uma 2a vez.
        /// </summary>
        /// <param name="blob">The blob inserted.</param>
        private void AttemptToRunTheHandlerAndReceiveTheCorrectHttpContextParameters(Blob blob)
        {
            // this is used to mock all requests
            const string UrlAuthority = "http://www.testland.com/";
            var queryString = new Dictionary<string, string>();
            queryString.Add("id", string.Empty);
            
            // this is the handler which will be tested
            var downloadHandler = new DownloadHandler(this.BlobsRepository);

            // 2.1) Que sem id no QueryString é retornado o status code 500
            this.HomeController.MockForTesting(); // generates the HttpContext necessary for the test.
            downloadHandler.ProcessRequest(HttpContext.Current);
            Assert.AreEqual<int>(500, HttpContext.Current.Response.StatusCode);

            // 2.2) Que com id errado (auy54y), é retornado um 404
            queryString["id"] = "auy54y";
            this.HomeController.MockForTesting(UrlAuthority, queryString); // generates the HttpContext necessary for the test.
            downloadHandler.ProcessRequest(HttpContext.Current);
            Assert.AreEqual<int>(404, HttpContext.Current.Response.StatusCode);

            // 2.3) Que com id errado (Guid.Empty()), é returnado um 404
            queryString["id"] = Guid.Empty.ToString();
            this.HomeController.MockForTesting(UrlAuthority, queryString); // generates the HttpContext necessary for the test.
            downloadHandler.ProcessRequest(HttpContext.Current);
            Assert.AreEqual<int>(404, HttpContext.Current.Response.StatusCode);

            // 2.4) Que com id correto foi possível retornar o arquivo 1 vez.
            queryString["id"] = blob.Id.ToString();
            this.HomeController.MockForTesting(UrlAuthority, queryString); // generates the HttpContext necessary for the test.
            downloadHandler.ProcessRequest(HttpContext.Current);
            Assert.AreEqual<int>(200, HttpContext.Current.Response.StatusCode);

            // 2.5) Que com id correto Que foi possível retornar o arquivo uma 2a vez.
            queryString["id"] = blob.Id.ToString();
            this.HomeController.MockForTesting(UrlAuthority, queryString); // generates the HttpContext necessary for the test.
            downloadHandler.ProcessRequest(HttpContext.Current);
            Assert.AreEqual<int>(200, HttpContext.Current.Response.StatusCode);
        }
    }
}


